import * as express from 'express';
import * as http from 'http';
import * as Koa from 'koa';
import * as bodyParser from 'koa-bodyparser';
import * as Router from 'koa-router';
import * as koaStatic from 'koa-static';
// import * as WebSocket from "uws";

import { fn } from 'moment';
import { Server } from '../src/Server';
import { ChatRoom } from './ChatRoom';

const port = Number(process.env.PORT || 2657);
const endpoint = 'localhost';

const app = new Koa();
const router = new Router();
app.use(bodyParser());

// Create HTTP & WebSocket servers
const server = http.createServer(app.callback());
const gameServer = new Server({
  // engine: WebSocket.Server,
  server,
});

// Register ChatRoom as "chat"
gameServer.register('chat', ChatRoom).
  // demonstrating public events.
  on('create', (room) => console.log('room created!', room.roomId)).
  on('join', (room, client) => console.log('client', client.id, 'joined', room.roomId)).
  on('leave', (room, client) => console.log('client', client.id, 'left', room.roomId)).
  on('dispose', (room) => console.log('room disposed!', room.roomId));

app.use(koaStatic(__dirname));

router.get('/something', async (ctx) => {
  console.log('something!', process.pid);
  console.log('GET /something');
  ctx.body = 'Hey!';
});

router.post('/something', async (ctx) => {
  console.log('POST /something');
  ctx.body = ctx.request.body;
});

app.use(router.routes());

const sleep = (time): Promise<any> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, 1000);
  });
};

gameServer.onShutdown(async () => {
  console.log('CUSTOM SHUTDOWN ROUTINE: STARTED');
  await sleep(1000);
  console.log('CUSTOM SHUTDOWN ROUTINE: FINISHED');
});

process.on('unhandledRejection', (r) => console.log(r));

gameServer.listen(port);

console.log(`Listening on ws://${endpoint}:${port}`);
